﻿using CaptchaGen;
using House.Common;
using House.DTO;
using House.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace House.Admin.Controllers
{
    
    public class HomeController : Controller
    {
        public IAdminUserService adminUserService { get; private set; }

        public HomeController(IAdminUserService admin)
        {
            adminUserService = admin;
        }
       
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {

            return View();
        }

        public ActionResult GetVerCode()
        {
            var code = new Random().Next(1000, 9999).ToString();
            TempData["code"] = code;
            var src = ImageFactory.GenerateImage(code, 60, 100, 15, 6);
            return File(src, "image/jpeg");
        }

        [HttpPost]
        public ActionResult Login(LoginDTO login)
        {
            if (ModelState.IsValid)
            {
                var code = TempData["code"];
                if (code==null)
                { 
                    return Json(AjaxResult<bool>.Fail("该验证码已失效"));
                }
                if (!login.VerCode.Equals(code))
                {
                    //{State:1,ErrorMessage:""}
                    return Json( AjaxResult<bool>.Fail("验证码不正确"));
                }
                //验证账号密码
                return Json(adminUserService.Login(login));
            }
            return Json( AjaxResult<bool>.Fail("请先输入数据")  );
        }

        public ActionResult LoginOut()
        {
            //获取cookie
            var cookie = Response.Cookies[FormsAuthentication.FormsCookieName];
            //将时间调为负数，使cookie过期
            cookie.Expires = DateTime.Now.AddDays(-1);
            //添加失败，自动清除
            Response.Cookies.Add(cookie);
            //Session.Abandon();
            return RedirectToAction("Login");
        }
    }
}